<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Tags extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function get_tags()
    {
        $tag_array = $this->get_tag_base(array());
        foreach($tag_array as $tag)
        {
            $tags[$tag['type']][] = $tag;
        }
        return $tags;
    }
    
    function get_tag_entries_by_eid($eid)
    {
        $quiry = $this->get_tag_base_by_eid($eid, 'tag');
        return $quiry->result_array();
    }
    
    function get_tag_entries()
    {
        $where = array(
            'type' => 'tag',
        );
        return $this->get_tag_base($where);
    }
    
    function get_category_entries()
    {
        $where = array(
            'type' => 'category',
        );
        return $this->get_tag_base($where);
    }
    
    function get_tag_base($where)
    {
        return $this->db->get_where('metas', $where)->result_array();
    }
    function get_tag_base_by_eid($eid, $type='tag')
    {
        $sql = "SELECT * FROM metas m LEFT JOIN relationships r ON r.mid=m.mid WHERE type='{$type}' AND r.eid = ?";
        $quiry = $this->db->query($sql, array($eid));
        return $quiry;
    }

    function get_tag_merchandise_by_id($id, $type='tag')
    {
        $sql = "SELECT * FROM metas m LEFT JOIN mer_metas mm ON mm.mid=m.mid WHERE type='{$type}' AND mm.mer_id = ?";
        $quiry = $this->db->query($sql, array($id));
        return $quiry->result_array();
    }

    function get_tag_monographic_by_monid($id, $type='tag')
    {
        $sql = "SELECT * FROM metas m LEFT JOIN mono_metas mm ON mm.mid=m.mid WHERE type='{$type}' AND mm.monid = ?";
        $quiry = $this->db->query($sql, array($id));
        return $quiry->result_array();
    }

    function add_entries_category($eid, $tags)
    {
        $this->add_entries($eid, $tags, 'category');
    }

    /**
     * 更新TAG
     *
     * @access global
     * @param mixed $eid Entries表ID
     * @param mixed $tags 要写的tag
     * @return void
     */
    function add_entries($eid, $tags, $type='tag')
    {
        if(!is_array($tags))
        {
            $tags = str_replace('，', ',', $tags);
            $tags = array_unique(array_map('trim', explode(',', $tags)));
        }

        /** count-1数据 */
        $sql = "SELECT * FROM metas m LEFT JOIN relationships r ON r.mid=m.mid WHERE type='{$type}' AND r.eid = ?";
        $quiry = $this->db->query($sql, array($eid));
        if($quiry->num_rows() > 0)
        {
            $metas_arr = $quiry->row_array();
            if($metas_arr['count'] > 1)
            {
                /** 统计数减一 */
                $sql = "UPDATE metas m, relationships r SET m.count = m.count - 1 WHERE r.mid=m.mid AND type='{$type}' AND r.eid = ?";
                $this->db->query($sql, array($eid));

                /** 清除关联 */
                $this->delete_relationships($eid);
            }
        }

        /** 插入tag */
        $insertTags = $this->set_tags($tags, $type);

        /** 写入关联 */
        $insertRelationships = array();
        if(is_array($insertTags))
        {
            foreach($insertTags as $tag)
            {
                $insertRelationships[] = array('eid'=>$eid,'mid'=>$tag);
            }
        }
        else
        {
            $insertRelationships[] = array('eid'=>$eid,'mid'=>$insertTags);
        }
        return $this->db->insert_batch('relationships', $insertRelationships);
    }

    /**
     * 更新TAG
     *
     * @access global
     * @param mixed $eid Entries表ID
     * @param mixed $tags 要写的tag
     * @return void
     */
    function add_merchandise($mer_id, $tags, $type='tag')
    {
        if(!is_array($tags))
        {
            $tags = str_replace('，', ',', $tags);
            $tags = array_unique(array_map('trim', explode(',', $tags)));
        }

         /** count-1数据 */
        $sql = "SELECT * FROM metas m LEFT JOIN mer_metas mm ON mm.mid=m.mid WHERE type='{$type}' AND mm.mer_id = ?";
        $quiry = $this->db->query($sql, array($mer_id));
        if($quiry->num_rows() > 0)
        {
            $metas_arr = $quiry->row_array();
            if($metas_arr['count'] > 1)
            {
                /** 统计数减一 */
                $sql = "UPDATE metas m, mer_metas mm SET m.count = m.count - 1 WHERE mm.mid=m.mid AND m.type='{$type}' AND mm.mer_id = ?";
                $this->db->query($sql, array($mer_id));
                /** 清除关联 */
                $this->delete_mer_metas($mer_id);
            }
        }

        /** 插入tag */
        $insertTags = $this->set_tags($tags, 'tag');

        /** 写入关联 */
        $insertMer_metas = array();
        if(is_array($insertTags))
        {
            foreach($insertTags as $tag)
            {
                $insertMer_metas[] = array('mer_id'=>$mer_id,'mid'=>$tag);
            }
        }
        else
        {
            $insertMer_metas[] = array('mer_id'=>$mer_id,'mid'=>$insertTags);
        }
        return $this->db->insert_batch('mer_metas', $insertMer_metas);
    }
    
    

    /**
     * 更新TAG
     *
     * @access global
     * @param mixed $answers_id Answers表ID
     * @param mixed $tags 要写的tag
     * @return void
     */
    function add_Answers($answers_id, $tags)
    {
        if(!is_array($tags))
        {
            $tags = str_replace('，', ',', $tags);
            $tags = array_unique(array_map('trim', explode(',', $tags)));
        }
        
         /** count-1数据 */
        $sql = "SELECT * FROM metas m LEFT JOIN answers_metas am ON am.mid=m.mid WHERE type='tag' AND am.answers_id = ?";
        $quiry = $this->db->query($sql, array($answers_id));
        if($quiry->num_rows() > 0)
        {
            $metas_arr = $quiry->row_array();
            if($metas_arr['count'] > 1)
            {
                /** 统计数减一 */
                $sql = "UPDATE metas m, answers_metas am SET m.count=m.count-1 WHERE am.mid=m.mid AND m.type='tag' AND am.answers_id = ?";
                $this->db->query($sql, array($answers_id));
                /** 清除关联 */
                $this->delete_answers_metas($answers_id);
            }
        }


        /** 插入tag */
        $insertTags = $this->set_tags($tags, 'tag');

        /** 写入关联 */
        $insertAnswers_metas = array();
        if(is_array($insertTags))
        {
            foreach($insertTags as $tag)
            {
                $insertAnswers_metas[] = array('answers_id'=>$answers_id,'mid'=>$tag);
            }
        }
        else
        {
            $insertAnswers_metas[] = array('answers_id'=>$answers_id,'mid'=>$insertTags);
        }
        return $this->db->insert_batch('answers_metas', $insertAnswers_metas);
    }

    /**
     * 更新TAG
     *
     * @access global
     * @param mixed  monographic 表ID
     * @param mixed $tags 要写的tag
     * @return void
     */
    function add_monographic($monid, $tags)
    {
        if(!is_array($tags))
        {
            $tags = str_replace('，', ',', $tags);
            $tags = array_unique(array_map('trim', explode(',', $tags)));
        }
        
         /** count-1数据 */
        $sql = "SELECT * FROM metas m LEFT JOIN mono_metas am ON am.mid=m.mid WHERE type='tag' AND am.monid = ?";
        $quiry = $this->db->query($sql, array($monid));
        if($quiry->num_rows() > 0)
        {
            $metas_arr = $quiry->row_array();
            if($metas_arr['count'] > 1)
            {
                /** 统计数减一 */
                $sql = "UPDATE metas m, mono_metas am SET m.count=m.count-1 WHERE am.mid=m.mid AND m.type='tag' AND am.monid = ?";
                $this->db->query($sql, array($monid));
                /** 清除关联 */
                $this->delete_mono_metas($monid);
            }
        }


        /** 插入tag */
        $insertTags = $this->set_tags($tags, 'tag');

        /** 写入关联 */
        $insertMonographic_metas = array();
        if(is_array($insertTags))
        {
            foreach($insertTags as $tag)
            {
                $insertMonographic_metas[] = array('monid'=>$monid,'mid'=>$tag);
            }
        }
        else
        {
            $insertMonographic_metas[] = array('monid'=>$monid,'mid'=>$insertTags);
        }
        return $this->db->insert_batch('mono_metas', $insertMonographic_metas);
    }
    /** 插入tag */
    function set_tags($tags, $type='tag')
    {
        $tags = is_array($tags) ? $tags : array($tags);
        $result = array();
        $this->load->helper('common');

        foreach($tags as $tag)
        {
            if (empty($tag)) continue;

            $sql = "SELECT * FROM metas WHERE type = '{$type}' AND name = ?";
            $quiry = $this->db->query($sql, $tag);
            if($quiry->num_rows() > 0)
            {
                $row = $quiry->row_array();
                $result[] = $row['mid'];
                /** 统计数加一 */
                $sql = "UPDATE metas SET count = count + 1 WHERE type='{$type}' AND mid = ?";
                $this->db->query($sql, array($row['mid']));
            }
            else
            {
                if($slug = slugName($tag))
                {
                    $this->db->insert('metas', array(
                        'slug'=>$slug,
                        'name'=>$tag,
                        'type'=>$type,
                        'count'=>1
                    ));
                    $result[] = $this->db->insert_id();
                }
            }
        }
        return is_array($tags) ? $result : current($result);
    }

    /** 清除关联 */
    public function delete_mono_metas($monid)
    {
       return $this->db->delete('mono_metas', array('monid' => $monid));
    }

    /** 清除关联 */
    public function delete_answers_metas($answers_id)
    {
       return $this->db->delete('answers_metas', array('answers_id' => $answers_id));
    }

    /** 清除关联 */
    public function delete_mer_metas($mer_id)
    {
       return $this->db->delete('mer_metas', array('mer_id' => $mer_id));
    }

    /** 清除关联 */
    public function delete_relationships($eid)
    {
       return $this->db->delete('relationships', array('eid' => $eid));
    }
}